from django.db import models
from django.conf import settings

from page.models import Page


class Difficulty(models.Model):
    name = models.CharField(max_length=255, unique=True, blank=False)

    def __unicode__(self):
        return self.name

    class Meta:
        db_table = u'difficulties'

class Question(models.Model):
    question = models.TextField(blank=False)
    difficulty = models.ForeignKey(Difficulty, null=True, blank=True)
    question_type = models.TextField()
    english = models.BooleanField()
    is_case_sensitive = models.BooleanField()

    correct_info = models.TextField(blank=True, null=True)
    wrong_info = models.TextField(blank=True, null=True)

    page = models.ForeignKey(Page, null=True, blank=True)

    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+', null=True, 
            blank=True)
    modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+', null=True, 
            blank=True)

    created = models.DateTimeField(auto_now_add=True, null=True)
    modified = models.DateTimeField(auto_now=True, null=True)

    trash = models.BooleanField()

    def __unicode__(self):
        return self.question

    def check_answer(self, answer):
        """
        Check if the given answer is correct for this question.
        Answers that are empty strings or None are always False.
        Return true if answer is correct otherwise false.
        """
        from question.question_type import QUESTION_TYPES
        if answer:
            result = QUESTION_TYPES.get(
                    self.question_type).check_answer(self, answer)
        else:
            result = False
        return result

    def correct_answer(self, answer):
        """
        Check if the given answer is correct for this question and also return
        the associated info. 
        Answers that are empty strings or None are always False.
        Return a list of true and correct info if answer is correct 
        otherwise a list of false and wrong info.
        """
        answer_is_correct = self.check_answer(answer)

        info = self.correct_info if answer_is_correct else self.wrong_info

        return [answer_is_correct, info]

    class Meta:
        db_table = u'questions'

class Answer(models.Model):
    answer = models.TextField(blank=False)

    class Meta:
        db_table = u'answers'

class Correct(models.Model):
    question = models.ForeignKey(Question)
    answer = models.ForeignKey(Answer)

    class Meta:
        db_table = u'correct'

class Wrong(models.Model):
    question = models.ForeignKey(Question)
    answer = models.ForeignKey(Answer)

    class Meta:
        db_table = u'wrong'
